import socket
import memcache

class yawhois:
  """simple whois parser for whois requests"""
  _domain = None
  _tld = None
  _sock = None
  _whois_server = None
  _whois_raw_response = None
  _parser = None
  _memcache = None
  _fqdn = None
  
  def __init__(self, fqdn, enable_memcache = None):
    """class init"""

    self._fqdn = fqdn
    
    if fqdn.count(".") == 1:
      self._domain, self._tld = fqdn.split(".")
    else:
      # this might an three part domain like something.co.uk
      self._domain, self._tld, temppart = fqdn.split(".")
      self._tld = self._tld + "." + temppart
    
    # enable memcache
    if enable_memcache:
      self._memcache = memcache.Client([enable_memcache], debug=0)

    # create tcp socket and query the whois server for this tld
    self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self._whois_server = self._tld + '.whois-servers.net'
    try:
      self._do_query()
    except:
      raise

    # import parser for this tld
    try:
      module = __import__("yawhois.tld." + self._tld.replace(".", "_") + "_parser",
	fromlist = [self._tld.replace(".", "_") + "_parser"])
      parser_class = getattr(module, self._tld.replace(".", "_") + "_parser")
      self._parser = parser_class(self._whois_raw_response, fqdn)
    except:
      raise

  def _do_query(self):
    """query the whois server for raw output"""
    try:
      response = None
      
      if self._memcache:
	response = self._memcache.get(self._whois_server + self._domain + self._tld)
	
      if not response:
	self._sock.connect(((self._whois_server, 43)))
	self._sock.send(self._fqdn + "\r\n")

	response = ''
	while True:
	  d = self._sock.recv(4096)
	  response += d
	  if d == '':
	    break

	if self._memcache:
	  self._memcache.set(self._whois_server + self._domain + self._tld, response)
	self._sock.close()

      self._whois_raw_response = response
    except:
      raise            

  def __getattr__(self, attr):
    """get attribute from child parser"""
    try:
      return getattr(self._parser, attr)
    except:
      raise
  
  def __str__(self):
    """Print all whois properties of domain"""
    return '\n'.join('%s: %s' % (attr, str(getattr(self._parser, attr))) for attr in self._parser.attrs())

# eof